import { mapGetters } from 'vuex'
import { isPc, isMobile, getViewport, getIP, getPlatform, DeepCloneData, isWxBrowser } from '@/utils'
import { initHanddrawBgmusic, playHanddrawBgmusic, pauseHanddrawBgmusic } from '@/utils/audio'

export default {
  components: {
    Loading: () => import('Comps/Loading/Handdraw'),
    Option: () => import('Comps/Overview/Option'),
    Option864: () => import('Comps/Overview/Option864'),
    Menu: () => import('Comps/Overview/Menu'),
    MenuContents: () => import('Modal/MenuContents'),
    Effect: () => import('Comps/Effect'),
  },
  data() {
    return {
      is864: $globalconfig.MODULES.IS_JIAPEI_PROGRAM_OPEN,
      isShowLoading: true,
      isShowPic: false,
      isShow: false,
      ew: 1190,
      img: null,
      imgX: 0,
      imgY: 0,
      scale: 1,
      imgScale: 1.5, // 缩放比例
      maxScale: 1.05,
      minScale: 0.95,
      imgNaturalSize: 0, // 图片原始尺寸
      ovvMarkTypeObj: {},
      ovvId: null,
      pointObj: {
        w: 30,
        h: 30,
        type: 0
      },
      markerList: [],
      isMute: true,
      isFinish: true,
      mouse: {x: 0, y: 0},
      downX: 0,
      downY: 0,
      mousePosition: {
        isDrag: false,
        x: 0,
        y: 0
      }
    }
  },
  computed: {
    ...mapGetters(['ovvData', 'loadInfo']),
    getLoadImage() {
      if (!this.loadInfo) return false
      if (this.loadInfo) {
        if (this.loadInfo.load_type == 1) {
          return true
        } else {
          if (this.ovvData) {
            if(isPc() && this.ovvData.loadinfo.pc_load_img) {
              return this.ovvData.loadinfo.pc_load_img
            }
            if(isMobile() && this.ovvData.loadinfo.load_img) {
              return this.ovvData.loadinfo.load_img
            }
          }
        }
      }

    },
    getOvvImage() {
      if (this.ovvData) {
        this.img = this.$refs.imgHook
        return this.ovvData.full_image_url
      }
    },
    getStartPic() {
      if (this.ovvData && this.ovvData.startpicurl) {
        let url = this.ovvData.startpicurl.indexOf('|') != -1 ? this.ovvData.startpicurl.split('|')[1] : this.ovvData.startpicurl
        return $globalconfig.URLS.API + url
      }
    },
    getMusic() {
      if (this.ovvData && this.ovvData.bgmusicurl) {
        // console.log(this.ovvData)
        return this.ovvData.full_bgmusic_url
      }
    },
    isShowEffect() {
      if(this.ovvData) {
        return this.ovvData.bgeffect
      }
    }
  },
  created() {
    this.vw = document.documentElement.clientWidth
    this.vh = document.documentElement.clientHeight
    this.ovvMarkTypeObj = this.$CONFIG.ovvMarkType

    this.ovvId = this.$route.params.id
  },
  mounted() {

    // 发送用户数据
    setTimeout(() => {
      //实例化城市查询类
      var cityData
      var userData = {
        sw: getViewport().VW,
        sh: getViewport().VH,
        ip: getIP(),
        city: '',
        region: '',
        type: getPlatform() ? 1 : 2,
        overview_id: this.ovvData ? this.ovvData.overview_id : '',
        userid: this.ovvData ? this.ovvData.user_id : '',
        type_id: 0,
      }

      try {
        let citysearch = new AMap.CitySearch()

        //自动获取用户IP，返回当前城市
        citysearch.getLocalCity((status, result) => {
          if (status === 'complete' && result.info === 'OK') {
            cityData = result
            userData.city = cityData ? cityData.city : ''
            userData.region = cityData ? cityData.province : ''
            this.$store.dispatch('sendCustomInfoOvv', userData)
          }
        })
      } catch (e) {
        this.$store.dispatch('sendCustomInfoOvv', userData)
      }
    }, 5000)
  },
  beforeDestroy () {
    this.pauseMusic()
  },
  methods: {
    loadImage() {
      if (this.getOvvImage) {
        var img = new Image()
        // this.img = img

        img.onload = () => {
          this.isShow = true
          this.$bar.finish()

          setTimeout(() => {
            this.resizeImage()
          }, 500)

          setTimeout(() => {
            if(!this.getLoadImage) {
              this.isShowPic = true
              this.hideStartPic()
            }
          }, 1000)
        }
        img.src = this.getOvvImage

        img.onerror = () => {
          this.$vgo.tip('加载失败', 'warning')
        }
      }
    },
    moveImage() {
      let step = this.imgY
      const move = () => {
        step += 12
        if(parseInt(this.img.style.top) > this.imgY / 4) {
          this.img.style.top = -step + 'px'
          timer = requestAnimationFrame(move)
        } else {
          this.loadMarkers()
          this.imgX = (this.vw - this.img.width * this.scale) / 2
          this.imgY = (this.vh - this.vw / (this.img.width / this.img.height) * this.scale) / 2
        }
      }
      cancelAnimationFrame(timer)
      var timer = requestAnimationFrame(move)
    },
    loadMarkers() {
      let isNewData = true
      if (this.ovvData.point_list && this.ovvData.point_list.length > 0 && this.ovvData.point_list[0].material_id == undefined) {
        isNewData = false
      }
      let tempArr = []
      if (this.ovvData && this.ovvData.point_list) {
        tempArr = DeepCloneData(this.ovvData.point_list)
      }
      // console.log(tempArr)
      let wi, hei
      if (!isNewData) {
        // 宽1200 高换算
        wi = 1200
        hei = wi * this.ovvData.imageheight / this.ovvData.imagewidth
      }
      // console.log(tempArr

      tempArr.map((marker,index)=>{//循环
        // 偏差修正
        // marker.y = marker.y + 20
        if (!isNewData) {
          // 兼容旧数据
          marker.x = marker.x * 100 / wi
          marker.y = marker.y * 100 / hei
          marker.material_id = -1
        }
       
        this.addMarkers(marker,index)
       
      })
    },
    addMarkers(marker,index) {
      console.log(marker,index);
      if(index==0||index==1||index==4||index==13||index==14){ 
        return
      }
      // if(index==15||id==index){
      //   return
      // }
      console.log(index);
      let self = this
      let _marker = document.createElement('div')//创建元素
      let oSpan = document.createElement('span')
      let oImg = document.createElement('img')
      let oSan = document.createElement('div')
      // if(marker.material_id==16||){
      //   _marker.style.display="none"
      // }
      oSpan.innerHTML = marker.name
      oSpan.className = 'xintext omit'
      oSan.className = 'daosanjiao'
      oImg.className = 'xinimage'
      // styletype=21显示图片框和倒三角
      oSpan.style.color = this.ovvData.custom_color || "#FFFFFF"
      if (this.ovvData.styletype == 21) {
        oImg.style.border = `3px solid ${this.ovvData.custom_color || "#FFFFFF"}`
        oSan.style.borderTop = `10px solid ${this.ovvData.styletype == 21?(this.ovvData.custom_color || "#FFFFFF"):"rgba(0,0,0,0)"}`
      } else {
        oSan.style.opacity = 0
        oImg.style.border = `3px solid rgba(0,0,0,0)`
      }
      
      _marker.className = 'ovv-item pos-a ovvitem'+(marker.material_id || 0)
      _marker.style.zIndex = 99
      _marker.setAttribute('id', marker.pano_id)
      this.setMarkerOffset(_marker, marker)
      // _marker.href = 'http://192.168.0.103:8082/#/panoview/' + marker.pano_id + '?ovv=' + self.ovvId
      // _marker.href = $globalconfig.URLS.PANO_VIEW_PREFIX + marker.pano_id + '?ovv=' + self.ovvId
      _marker.onclick = () => {
        // const url = '/panoview/' + marker.pano_id + '?ovv=' + self.ovvId + '&t=' + Date.now()
        // $VM.$router.push(url)
        // const url = $globalconfig.URLS.PANO_VIEW_PREFIX + marker.pano_id + '?ovv=' + self.ovvId + '&t=' + Date.now()
        // window.location.replace(url)
        // setTimeout(() => {
        //   window.location.reload()
        // }, 20)
        let url = ''
        if(this.ovvData.styleeffect > 0) {
          _marker.className = `ovv-item pos-a ovvitem${(marker.material_id || 0)} animated infinite ${this.ovvMarkTypeObj.effect[this.ovvData.styleeffect]}`
          setTimeout(() => {
            url = marker.preview_url + '?tour=' + self.ovvId + '&t=' + Date.now()
            // console.log(url)
            window.open(url, '_self')
            pauseHanddrawBgmusic()
          }, 3000)
        } else {
          url = marker.preview_url + '?tour=' + self.ovvId + '&t=' + Date.now()
          // console.log(url)
          window.open(url, '_self')
          pauseHanddrawBgmusic()
        }

      }

      if (this.ovvData.styletype == 21) {
        oImg.src = marker.full_icon_src
      } else {
        if (marker.material_id == -1) {
          // 旧数据
          oImg.src = this.ovvMarkTypeObj.imgs[this.ovvData.styletype + 1]
        } else {
          oImg.src = this.ovvMarkTypeObj.imgs[this.ovvData.styletype]
        }
      }
      // if(this.ovvData.styletype > 0 && this.ovvData.styleeffect > 0) {
      //   oImg.className = `animated infinite ${this.ovvMarkTypeObj.effect[this.ovvData.styleeffect]}`
      // }
      if(isMobile()) {
        oImg.style.width = this.pointObj.w + 'px'
        oImg.style.height = this.pointObj.h + 'px'
      } else {
        oImg.style.width = this.pointObj.w + 'px'
        oImg.style.height = this.pointObj.h + 'px'
      }
      // oImg.style.marginLeft = -this.pointObj.w / 2 + 'px'
      _marker.appendChild(oSpan)
      _marker.appendChild(oImg)
      _marker.appendChild(oSan)

      this.markerList.push({
        marker: _marker,
        param: marker
      })

      this.$refs.imgWrap.appendChild(_marker)
      return _marker
    },
    reloadMarkers() {
      this.markerList.map((el, index) => {
        this.setMarkerOffset(el.marker, el.param, {x: el.param.x, y: el.param.y})
      })
    },
    setMarkerOffset(marker, position) {
      let offset = this.getImagePos()
      // let eh = this.ovvData.imageheight / (this.ovvData.imagewidth / this.ew)

      // let l = parseInt(this.img.width * (position.x / this.ew)+ offset.left + this.pointObj.w/2)
      // let t = parseInt(this.img.height * (position.y / eh) + offset.top - this.pointObj.w)
      let l = this.img.width * position.x / 100 + offset.left - this.pointObj.w/2
      let t = this.img.height * position.y / 100 + offset.top - this.pointObj.h/2
      // 误差5
      marker.style.left = l-5 + 'px'
      // 误差32
      marker.style.top =  t-32 + 'px'
      // console.log(l, t)

      this.isFinish = true
    },
    playMusic() {
      playHanddrawBgmusic()
      this.isMute = true
    },
    pauseMusic() {
      pauseHanddrawBgmusic()
      this.isMute = false
    },
    toggleMusic() {
      if (this.isMute) {
        pauseHanddrawBgmusic()
      } else {
        playHanddrawBgmusic()
      }
      this.isMute = !this.isMute
    },
    hideStartPic(isClick) {
      if(isClick) {
        this.isShowPic = false
        return
      }
      let num = 3
      let timer
      const countdown = () => {
        timer = setTimeout(() => {
          if(num > 0) {
            num--
            countdown()
          } else {
            clearTimeout(timer)
            this.isShowPic = false
          }
        }, 1000)
      }
      countdown()
    },
    closeLoading() {
      this.isShowLoading = false
      setTimeout(() => {
        this.isShowPic = true
        this.hideStartPic()
      }, 3000)
    },
    getStyle(el, name) {
      return getComputedStyle(el)[name]
    },
    getImageDim() {
      let w0 = this.img.width
      let h0 = this.img.height
      return {
        w: w0,
        h: h0
      }
    },
    getImagePos() {
      let left = parseFloat(this.getStyle(this.img, 'left'))
      let top = parseFloat(this.getStyle(this.img, 'top'))

      return {
        left,
        top
      }
    }
  },
}
